<template>
  <div>
    <t-card class="list-card-container" :bordered="false">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="formDialogVisible = true"> 新增权限 </t-button>
          <t-space>
            <t-select v-model="roleId" :options="options" :onChange="clickHandler" autoWidth placeholder="请选择角色"
              class="rent-space"></t-select>
          </t-space>
        </div>
      </t-row>
      <t-table :data="data" :columns="COLUMNS" :row-key="rowKey" vertical-align="top" :hover="true"
        :pagination="pagination" :selected-row-keys="selectedRowKeys" :loading="dataLoading">
        <template #state="{ row }">
          <t-tag v-if="row.state === ROLE_STATUS.YES" theme="success" variant="light"> 开启 </t-tag>
          <t-tag v-if="row.state === ROLE_STATUS.NO" theme="danger" variant="light"> 停用 </t-tag>
        </template>
        <template #op="slotProps">
          <t-space>
            <t-link theme="primary" @click="handleEdit(slotProps)">修改</t-link>
            <t-link theme="danger" @click="handleClickDelete(slotProps)">删除</t-link>
          </t-space>
        </template>
      </t-table>
    </t-card>

    <t-dialog v-model:visible="deleteVisible" body="确认是否删除？" header="提示" :on-cancel="onCancel"
      @confirm="onConfirmDelete" />

    <dialog-form v-model:visible="formDialogVisible" :roleId="roleId" :roleArr="options" :data="formData"
      @refreshData="fetchData()" />
  </div>
</template>

<script lang="ts">
export default {
  name: 'AdminPermission',
};
</script>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';

import { getPermission, deletePermission } from '@/api/admin/permission';
import { getRole } from '@/api/admin/role';
import { ROLE_STATUS } from '@/constants';
import { COLUMNS } from './constants';

import type { FormData } from './components/PermissionForm.vue';
import DialogForm from './components/PermissionForm.vue';

// 必需。table唯一标识一行数据的字段名，
const rowKey = 'id';

// 新增功能
const INITIAL_DATA: FormData = {
  id: 0,
  controller: '',
  action: '',
  admin_role_id: 0
};
const formData = ref({ ...INITIAL_DATA });
const formDialogVisible = ref(false);

// 列表查询功能，data为列表数据
const data = ref([]);
const pagination = ref({
  defaultPageSize: 20,
  total: 100,
  defaultCurrent: 1,
});
const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const { list } = await getPermission({ admin_role_id: roleId.value });
    data.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    if (e.response && e.response.data.code === 995) {
      MessagePlugin.error(e.response.data.message);
    } else {
      MessagePlugin.error('系统错误');
    }
  } finally {
    dataLoading.value = false;
  }
};
// 用于在组件挂载到 DOM 上之后执行一些操作
onMounted(() => {
  queryRole();
  fetchData();
});

// 修改功能
const handleEdit = (row: { row: any }) => {
  formDialogVisible.value = true;
  formData.value = { ...row.row };
};

// 删除功能
const deleteIdx = ref(-1);
const deleteVisible = ref(false);
const selectedRowKeys = ref([1, 2]);
const resetIdx = () => {
  deleteIdx.value = -1;
};
const handleClickDelete = (row: { row: any }) => {
  deleteVisible.value = true;
  deleteIdx.value = row.row.id;
};
const onConfirmDelete = async () => {
  // 真实业务请发起请求
  try {
    await deletePermission({ id: deleteIdx.value });
    fetchData();
    resetIdx();
  } catch (e) {
    if (e.response && e.response.data.code === 995) {
      MessagePlugin.error(e.response.data.message);
    } else {
      MessagePlugin.error('系统错误');
    }
  } finally {
    deleteVisible.value = false;
  }
};
const onCancel = () => {
  resetIdx();
};

// 角色选择框
const roleId = ref();
const options = ref([]);
const queryRole = async () => {
  try {
    const { list } = await getRole();
    list.forEach((element, index) => {
      options.value.push({ label: element.name, value: element.id });
      if (index == 0) {
        roleId.value = element.id;
      }
    });
  } catch (e) {
    if (e.response && e.response.data.code === 995) {
      MessagePlugin.error(e.response.data.message);
    } else {
      MessagePlugin.error('系统错误');
    }
  }
}
const clickHandler = (value: any) => {
  roleId.value = value;
  fetchData();
};
</script>

<style lang="less" scoped>
.list-card-container {
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

  :deep(.t-card__body) {
    padding: 0;
  }
}

.left-operation-container {
  display: flex;
  align-items: center;
  margin-bottom: var(--td-comp-margin-xxl);
}

.rent-space {
  margin-left: var(--td-comp-margin-xxl);
}
</style>
